package com.wyp.controller.student;

import com.wyp.User.User;
import com.wyp.pojo.Apartments;
import com.wyp.pojo.Examinees;
import com.wyp.service.impl.ApartmentsServiceImpl;
import com.wyp.service.impl.ExamineesServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/student")
public class StudentLoginController {

    @Autowired
    private ExamineesServiceImpl examineesService;

    @Autowired
    private ApartmentsServiceImpl apartmentsService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @RequestMapping("/student_logout.html")
    public String logout() {
        return "redirect:/student/student_login.html";
    }

    @GetMapping({"/student_login.html", "/"})
    public String login() {
        return "student/student_login";
    }

    @RequestMapping("/student_error.html")
    public String toerror(HttpServletRequest request, Model model) {
        AuthenticationException exception =
                (AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        model.addAttribute("lerrormsg", exception.getMessage());
        return "student/student_login";
    }

    @PostMapping("/student_login.html")
    public String tologin(
            @RequestParam("registerUsername") String username,
            @RequestParam("registerApartment") int apartment,
            @RequestParam("registerGender") boolean gender,
            @RequestParam("registerNumber") String number,
            @RequestParam("registerPassword") String password,
            Model model
    ) {
        Examinees examinees = new Examinees();
        examinees.setStuname(username);
        examinees.setApartmentid(apartment);
        examinees.setGender(gender);
        examinees.setStuaccount(number);
        examinees.setStupassword(encoder.encode(password));
        boolean info = examineesService.addExaminees(examinees);
        if (info) {
            model.addAttribute("info", "注册成功");
            return "student/student_login";
        } else {
            model.addAttribute("info", "注册失败");
            return "student/student_register";
        }
    }


    @RequestMapping("/student_index.html")
    public String toIndex(
            Model model,
            HttpSession session) {
        if (session.getAttribute("examinee") == null) {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            if (auth.getPrincipal() instanceof User) {
                User user = (User) auth.getPrincipal();
                if (("ROLE_STU").compareTo((String.valueOf(((List) user.getAuthorities()).get(0)))) == 0) {
                    Map<String, Object> examinees = examineesService.findByStuaccount(user.getUsername());
                    session.setAttribute("examinee", examinees);
                    return "student/student_index";
                } else {
                    return "student/student_login";
                }
            } else {
                return "student/student_login";
            }
        } else {
            return "student/student_index";
        }
    }

    @GetMapping("/student_register.html")
    public String toRegister(Model model) {
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        return "student/student_register";
    }

    @GetMapping("/student_toupdate.html")
    public String toupdatestu(
            HttpSession session,
            Model model
    ) {
        Map<String, Object> stu = (Map<String, Object>) session.getAttribute("examinee");
        Map<String, Object> updatestu = examineesService.findByStuaccount((String) stu.get("stuaccount"));
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        model.addAttribute("updatestu", updatestu);
        return "student/student_update";
    }

    @RequestMapping("/findRegisterByUsername")
    @ResponseBody
    public Map<String, Object> findRegisterByUsername(String username) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean isExist;
        if (examineesService.findByStuaccount(username) != null) {
            isExist = true;
        } else {
            isExist = false;
        }
        resultMap.put("isExist", isExist);
        return resultMap;
    }

    @PostMapping("/student_update.html")
    public String stupdate(
            HttpSession session,
            @RequestParam("registerUsername") String username,
            @RequestParam("registerApartment") int apartment,
            @RequestParam("registerGender") boolean gender,
            Model model
    ) {
        Map<String, Object> examinee = (Map<String, Object>) session.getAttribute("examinee");
        Examinees examinees = new Examinees();
        examinees.setStuid((int) examinee.get("stuid"));
        examinees.setStuname(username);
        examinees.setApartmentid(apartment);
        examinees.setGender(gender);
        examinees.setStuaccount((String) examinee.get("stuaccount"));
        examinees.setStupassword((String) examinee.get("stupassword"));
        boolean info = examineesService.updateExaminees(examinees);
        return "redirect:/student/student_index.html";
    }

    @GetMapping("/student_passupdate.html")
    public String tostupassupdate(
            HttpSession session,
            Model model
    ) {
        Map<String, Object> stu = (Map<String, Object>) session.getAttribute("examinee");
        Map<String, Object> updatestu = examineesService.findByStuaccount((String) stu.get("stuaccount"));
        model.addAttribute("updatestu", updatestu);
        return "student/student_passupdate";
    }

    @PostMapping("/student_passupdate.html")
    public String stupassupdate(
            @RequestParam("registerNumber") String number,
            @RequestParam("registerPassword") String password,
            Model model
    ) {
        Map<String, Object> examinee = examineesService.findByStuaccount(number);
        Examinees examinees = new Examinees();
        examinees.setStuid((int) examinee.get("stuid"));
        examinees.setStuname((String) examinee.get("stuname"));
        examinees.setApartmentid((int) examinee.get("apartmentid"));
        examinees.setGender((Boolean) examinee.get("gender"));
        examinees.setStuaccount(number);
        examinees.setStupassword(encoder.encode(password));
        boolean info = examineesService.updateExaminees(examinees);
        return "redirect:/student/student_toupdate.html";

    }
}

